package com.epoint.androidphone.mobileoa.ui.schedule;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;
import com.epoint.androidmobile.bizlogic.schedule.model.RcModel;
import com.epoint.androidmobile.bizlogic.schedule.model.ServerRcModel;
import com.epoint.androidmobile.bizlogic.schedule.task.GetScheduleListTask;
import com.epoint.androidmobile.core.control.AlertUtil;
import com.epoint.androidmobile.core.date.DateUtil;
import com.epoint.androidmobile.core.string.StringHelp;
import com.epoint.androidmobile.core.xml.XMLUtil;
import com.epoint.androidmobile.bizlogic.schedule.task.Schedule_DeleteTask;
/**
 * @author liyc
 * @time 2013-5-5 下午11:43:45
 * @annomation 
 */
public class ScheduleMainView extends SuperPhonePage{

	private long getScheduleListId,deleteScheduleId;

	private GridView gvCal;

	List<RcModel> rcList = new ArrayList<RcModel>();
	HashMap<String, RcModel> rcMap = new HashMap<String, RcModel>();
	CalAdapter adapter = new CalAdapter();

	Date today,visibdate;
	Button btPreMonth,btNextMonth,btGotoToday,btChooseDate,btAddSchedule;
	List<ServerRcModel> allServerRcList = new ArrayList<ServerRcModel>();

	ListView lvRc;

	List<ServerRcModel> chooseDayServerRcList = new ArrayList<ServerRcModel>();
	RcListAdapter rclistAdapter = new RcListAdapter();

	int clickPosition;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addContentViewAndTitle(R.layout.schedulemain, getIntent().getStringExtra("viewtitle"));

		btPreMonth = (Button) findViewById(R.id.btPreMonth);
		btPreMonth.setOnClickListener(this);
		btNextMonth = (Button) findViewById(R.id.btNextMonth);
		btNextMonth.setOnClickListener(this);
		btGotoToday = (Button) findViewById(R.id.btGotoToday);
		btGotoToday.setOnClickListener(this);
		btChooseDate = (Button) findViewById(R.id.btChooseDate);
		btChooseDate.setOnClickListener(this);
		btAddSchedule = (Button) findViewById(R.id.btAddSchedule);
		btAddSchedule.setOnClickListener(this);
		lvRc = (ListView) findViewById(R.id.lvRc);
		lvRc.setAdapter(rclistAdapter);
		lvRc.setOnItemClickListener(this);
		lvRc.setOnItemLongClickListener(this);

		gvCal = (GridView) findViewById(R.id.gvCal);
		gvCal.setOnItemClickListener(this);
		gvCal.setAdapter(adapter);

		today = new Date();
		visibdate = new Date();
		visibdate.setDate(1);
		updateCal(visibdate);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final int fp = position;
		AlertUtil.showAlertMenu(this, "操作", new String[]{"编辑","删除"}, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which==0)
				{
					go2Edit(fp);
				}
				else if(which==1)
				{
					ServerRcModel srm = chooseDayServerRcList.get(fp);
					HashMap<String, Object> params = getPassMap();
					params.put("ActivityID", srm.ActivityID);
					deleteScheduleId = new Schedule_DeleteTask(ScheduleMainView.this, params).startTask();
				}
					
			}
		}
				);
		
		return super.onItemLongClick(parent, view, position, id);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if(parent==gvCal){
			if(position>=7){
				if((position-7)<rcList.size()){
					if(rcList.get(position-7)!=null)
					{
						clickPosition = position-7;
						RcModel r = rcList.get(position-7);
						chooseDayServerRcList = r.serverRcList;
						rclistAdapter.notifyDataSetChanged();
						getTvTitle().setText(DateUtil.convertDate(r.date, "yyyy年MM月dd日"));
					}
				}
			}
		}
		else if(parent==lvRc)
		{
			go2Edit(position);
		}
	}

	public void go2Edit(int position){
		Intent it = new Intent(getContext(), ScheduleAddView.class);
		it.putExtra("operateflag", 2);//1添加,2修改
		it.putExtra("model", chooseDayServerRcList.get(position));
		startActivity(it);
	}

	public void moveDate(int value)
	{
		chooseDayServerRcList.clear();
		System.out.println(visibdate);
		Calendar c = Calendar.getInstance();
		c.setTime(visibdate);
		c.add(Calendar.MONTH, value);

		visibdate = c.getTime();
		updateCal(c.getTime());
		System.out.println(visibdate);
	}

	public void moveToToday()
	{
		chooseDayServerRcList.clear();
		visibdate = new Date();
		visibdate.setDate(1);
		updateCal(visibdate);
	}

	public void chooseDate()
	{
		AlertUtil.showDatePickDialog(this, new OnDateSetListener() {

			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				chooseDayServerRcList.clear();
				visibdate.setYear(year-1900);
				visibdate.setMonth(monthOfYear);
				updateCal(visibdate);
			}
		}, "请选择日期");
	}

	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		super.onClick(v);
		if(v==btNextMonth)
		{
			moveDate(1);
		}
		else if(v==btPreMonth)
		{
			moveDate(-1);
		}
		else if(v==btGotoToday)
		{
			moveToToday();
		}
		else if(v==btChooseDate)
		{
			chooseDate();
		}
		else if(v==btAddSchedule)
		{
			Intent it = new Intent(this, ScheduleAddView.class);
			it.putExtra("operateflag", 1);//1添加,2修改
			startActivity(it);
		}
	}



	public void updateCal(Date currentDate)
	{
		rcList.clear();
		rcMap.clear();
		//当前月
		int currentMonthday = DateUtil.getMonthLastDay(currentDate.getYear(), currentDate.getMonth()+1);
		int firstDaysWeek = DateUtil.getWeekByDateTime(currentDate);

		for(int i=0;i<firstDaysWeek;i++)
		{
			Calendar c = Calendar.getInstance();
			c.setTime(currentDate);
			c.add(Calendar.DATE, -(firstDaysWeek-i));

			RcModel rm = new RcModel();
			rm.date = c.getTime();
			rm.day = rm.date.getDate();
			rm.monthType = -1;

			rcMap.put(DateUtil.convertDate(rm.date, DateUtil.DateFormat_24), rm);
			rcList.add(rm);
		}

		for(int i=0;i<currentMonthday;i++)
		{
			Date d = new Date();
			d.setYear(currentDate.getYear());
			d.setMonth(currentDate.getMonth());
			d.setDate(i+1);
			RcModel rm = new RcModel();
			rm.day = i+1;
			rm.date = d;
			rm.monthType = 0;
			rcList.add(rm); 
			rcMap.put(DateUtil.convertDate(rm.date, DateUtil.DateFormat_24), rm);
		}

		int remainNextDays = 42 - rcList.size();
		for(int i=0;i<remainNextDays;i++)
		{
			Calendar c = Calendar.getInstance();
			c.setTime(currentDate);
			c.set(Calendar.DATE, currentMonthday);
			c.add(Calendar.DATE, i+1);

			RcModel rm = new RcModel();
			rm.date = c.getTime();
			rm.day = rm.date.getDate();
			rm.monthType = 1;
			rcList.add(rm);
			rcMap.put(DateUtil.convertDate(rm.date, DateUtil.DateFormat_24), rm);
		}

		adapter.notifyDataSetChanged();
		getTvTitle().setText(DateUtil.convertDate(currentDate, "yyyy年MM月"));

		getServerScheduleListDate("", DateUtil.convertDate(rcList.get(0).date, "yyyy-MM-dd"), DateUtil.convertDate(rcList.get(rcList.size()-1).date, "yyyy-MM-dd"));
	}

	void getServerScheduleListDate(String keyword,String fromDateTime,String toDateTime)
	{
		HashMap<String, Object> params = getPassMap();
		params.put("KeyWord", keyword);
		params.put("FromDateTime", fromDateTime);
		params.put("ToDateTime", toDateTime);

		showTopProgressBar();
		getScheduleListId = new GetScheduleListTask(this, params).startTask();
	}

	@Override
	public void refreshUI(long taskId, Object obj) {
		super.refreshUI(taskId, obj);
		if(taskId==getScheduleListId)
		{
			if (validateXML(obj)) {

				String bs = obj.toString();
				String UserArea = StringHelp.getXMLAtt(bs, "UserArea");
				allServerRcList = XMLUtil.DomAnalysisCommon(UserArea, ServerRcModel.class);

				System.out.println(allServerRcList.size());
				for(int i=0;i<rcList.size();i++)
				{
					RcModel rm = rcList.get(i);
					String rcdateStr = DateUtil.convertDate(rm.date, "yyyy-MM-dd");
					for(int j=0;j<allServerRcList.size();j++)
					{
						ServerRcModel srm = allServerRcList.get(j);

						String FromDateTime = srm.FromDateTime.substring(0, 10);
						String ToDateTime = srm.ToDateTime.substring(0, 10);
						if(rcdateStr.equals(FromDateTime))
						{
							rm.serverRcList.add(srm);
						}
						if(!FromDateTime.equals(ToDateTime)&&rcdateStr.equals(ToDateTime))
						{
							rm.serverRcList.add(srm);
						}
					}
					rcList.set(i, rm);
				}

				adapter.notifyDataSetChanged();

			}
		}
		else if(deleteScheduleId==taskId)
		{
			if (validateXML(obj)) {
				Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
				updateCal(visibdate);
			}
		}
	}

	class CalAdapter extends BaseAdapter
	{

		@Override
		public int getCount() {
			return 49;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv = new TextView(getContext());
			LinearLayout ll = new LinearLayout(getContext());
			ll.addView(tv,new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			ll.setBackgroundColor(Color.WHITE);
			tv.setHeight((gvCal.getHeight()-15)/7);
			tv.setGravity(Gravity.CENTER);
			tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
			tv.setTextColor(Color.BLACK);
			tv.setBackgroundColor(Color.WHITE);
			if(position<7)
			{
				tv.setHeight((gvCal.getHeight()-15)/7 - 10);
				tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
				//				tv.setHeight(gvCal.getHeight()/7-12);
				tv.setText(DateUtil.getWeekNameByNum(position+1));
				tv.setBackgroundColor(getResources().getColor(R.color.cal_week_bg));
				tv.setTextColor(getResources().getColor(R.color.white));
			}
			else
			{
				//				tv.setHeight(gvCal.getHeight()/7-1);
				//				tv.setTypeface(Typeface.createFromAsset(getAssets(),"fonts/MACTYPE.TTF"));

				if((position-7)<rcList.size()){
					if(rcList.get(position-7)!=null)
					{
						RcModel r = rcList.get(position-7);
						tv.setText(r.day+"");
						tv.setTextColor(Color.BLACK);
						if(r.monthType!=0)
						{
							tv.setTextColor(Color.GRAY);
						}
						//						tv.setBackgroundResource(R.drawable.mark_white);

						if(visibdate.getMonth()==today.getMonth()){
							if(r.date.getYear()==today.getYear()
									&&r.date.getMonth()==today.getMonth()
									&&r.date.getDate()==today.getDate())
							{
								tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
								tv.setTextColor(Color.RED);
								getTvTitle().setText(DateUtil.convertDate(r.date, "yyyy年MM月dd日"));
								chooseDayServerRcList = r.serverRcList;
								rclistAdapter.notifyDataSetChanged();
							}
						}
						if(r.serverRcList!=null){
							if(r.serverRcList.size()>0)
							{
								tv.setBackgroundResource(R.drawable.mark_white);
							}
						}
					}
				}

			}
			return ll;
		}
	}

	class RcListAdapter extends BaseAdapter
	{

		@Override
		public int getCount() {
			return chooseDayServerRcList.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView tv = new TextView(getContext());
			tv.setPadding(10, 15, 10, 15);
			tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
			tv.setTextColor(Color.BLACK);
			tv.setBackgroundResource(R.drawable.listbg1);
			ServerRcModel r = chooseDayServerRcList.get(position);
			String fromtime = r.FromDateTime.substring(11, r.FromDateTime.length());
			String totime = r.ToDateTime.substring(11, r.ToDateTime.length());
			tv.setText(fromtime +" "+ totime + " "+ r.Subject);
			return tv;
		}

	}
}
